package com.jukte.recipe.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;


public class DBContentProvider extends ContentProvider{

	private DatabaseHelper mDbHelper;

	private class DatabaseHelper extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "recipe";
		private static final int DATABASE_VERSION = 1;
		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION); 
		}

		@Override
		public void onCreate(SQLiteDatabase database) {
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {}

	}
	//content Provider Override
	@Override
	public int delete(Uri uri, String where, String[] selectionArgs) {
		 String table = getTableName(uri);
	     SQLiteDatabase dataBase=mDbHelper.getWritableDatabase();
	     return dataBase.delete(table, where, selectionArgs);
	}
	@Override
	public String getType(Uri uri) {
		return null;
	}
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase mDB = mDbHelper.getWritableDatabase();
		long rowID = mDB.insert(getTableName(uri), null, values);
		if (rowID > 0){
			Uri _uri = ContentUris.withAppendedId(DBAdapter.CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		throw new SQLException("Failed to add a record into " + uri);
	}
	@Override
	public boolean onCreate() {
		mDbHelper = new  DatabaseHelper(getContext());
	      /**
	       * Create a write able database which will trigger its 
	       * creation if it doesn't already exist.
	       */
		return (mDbHelper == null) ? false : true;
	}
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) {
		String table =getTableName(uri);
		SQLiteDatabase database = mDbHelper.getReadableDatabase();
		Cursor cursor =database.query(table,  projection, selection, selectionArgs, null, null, sortOrder);
		     return cursor;
	}
	@Override
	public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) {
		String table = getTableName(uri);
		SQLiteDatabase database = mDbHelper.getWritableDatabase();  
		return database.update(table, values, selection, selectionArgs);
	}
	public String getTableName(Uri uri){
		String value = uri.getLastPathSegment();
		return value;
	}
	
	public Cursor rawQuery(String sql, String[] selectionArgs){
		SQLiteDatabase database = mDbHelper.getReadableDatabase();
		return database.rawQuery(sql, selectionArgs);
	}

}